<template>
  <view class="container">
    <view class="count">消息（{{ count }}）</view>
    <scroll-view scroll-y @scrolltolower="loadMore" enable-flex class="list">
      <view class="box" @click="href(index)" v-for="(item, index) in list" :key="index">
        <image class="icon" :src="'../../static/images/msg-icon'+ item.type +'.png'"></image>
        <view class="info-box">
          <view class="title">{{ item.title }}</view>
          <view class="content">{{ item.content }}</view>
        </view>
        <view class="time">{{ item.create_time_desc }}</view>
      </view>
    </scroll-view>

    <view id="mask" v-if="show_login" @click="empty">
      <view class="mask-content" @click.stop="empty">
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="username" class="input" placeholder="请输入昵称">
          </view>

          <view class="agree-box">
            <button hover-class="none" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <view class="button cancel" @click="this.show_login = false">取消</view>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>
  </view>
</template>

<script>
import http from '@/utils/http'

export default {
  data() {
    return {
      count: 0,
      list: [],
      page: 1,
      pagesize: 10,
      show_login: false,
      login_to_url: '',// 登录之后跳转的页面
      privacyContractName: '《金翼隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      username: '',
    };
  },

  onShow: function (){
    this.page = 1;
    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0;

    if (!user_id) {
      uni.showLoading({
        title: '自动登录中...',
        mask: true
      })

      uni.login({
        success: result => {
          var code = result.code;

          this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
            uni.hideLoading();
            if (res.data.result == 1) {
              var user_id = res.data.data;
              uni.setStorageSync('user_id', user_id)

              this.$http.post('/index/Api/getUserProve', {user_id}).then(resProve => {
                if(resProve.data.result == 1){
                  var {student_prove_id, company_prove_id} = resProve.data.data;
                  uni.setStorageSync('student_prove_id', student_prove_id);
                  uni.setStorageSync('company_prove_id', company_prove_id);
                }
              })
              this.msgList();
            } else {
              this.show_login = true;
            }
          })
        }
      })
    } else {
      this.msgList();
    }
  },

  methods: {
    loadMore: function (){
      this.msgList(this.page + 1)
    },

    empty: function () {
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result == 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result == 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result == 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.$http.post('/index/Api/getUserProve', {user_id}).then(resProve => {
                      if (resProve.data.result == 1) {
                        var {student_prove_id, company_prove_id} = resProve.data.data;
                        uni.setStorageSync('student_prove_id', student_prove_id);
                        uni.setStorageSync('company_prove_id', company_prove_id);
                      }
                    })

                    this.show_login = false;

                    this.msgList();
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'none'
                })
              }
            })
          }
        })
      }
    },

    href: function (index){
      var list = this.list;

      //0：平台公告，1：岗位报名，2：项目申报，3：项目补贴申请，4：岗位报名处理
      switch (list[index].type) {
        case 1:
          // 岗位报名
          if(list[index].is_edit){
            uni.navigateTo({
              url: '/pages/join_post/join_post?project_id=' + list[index].project_id + '&post_id=' + list[index].post_id
            })
          }
          break;
        case 2:
          // 项目申报
          if(list[index].is_edit){
            uni.navigateTo({
              url: '/pages/apply_project/apply_project?id=' + list[index].to_id
            })
          }else{
            uni.navigateTo({
              url: '/pages/project_detail/project_detail?id=' + list[index].to_id
            })
          }
          break;
        case 3:
          // 项目补贴申请
          if(list[index].is_edit){
            uni.navigateTo({
              url: '/pages/apply_subsidy/apply_subsidy?project_id=' + list[index].project_id
            })
          }
          break;
        case 4:
          // 岗位报名处理
          uni.navigateTo({
            url: '/pages/join_status_detail/join_status_detail?id=' + list[index].to_id
          })
          break;
      }
    },

    msgList: function (incPage = 0){
      var page = incPage ? incPage : this.page;

      uni.showLoading({
        title: '数据加载中...',
        mask: true
      })

      this.$http.post('/index/Api/msgList', {
        user_id: uni.getStorageSync('user_id'),
        page: page,
        pagesize: this.pagesize
      }).then((res) => {
        if (res.data.result == 1) {
          if (page == 1) {
            this.list = res.data.data.list;
            this.count = res.data.data.count;
          } else {
            // 加载更多
            var list = this.list;

            for (var i = 0; i < res.data.data.list.length; i++) {
              list.push(res.data.data.list[i]);
            }

            this.list = list;
            this.page = page;
          }

          setTimeout(() => {
            uni.hideLoading();
          }, 500)
        } else {
          if (page == 1) this.list = [];

          uni.hideLoading();
          this.$common.doErrorResult(res);
        }
      })
    },
  },
}
</script>

<style lang="scss">
.container{
  background: #f5f5f5;
  .count{
    font-size: 36rpx;
    color: #3D3D3D;
    margin-left: 20rpx;
    height: 70rpx;
  }
  .list{
    background: #fff;
    padding: 0 20rpx;
    width: calc(100% - 40rpx);
    height: calc(100vh - 70rpx);
    border-radius: 20rpx 20rpx 0 0;
    .box{
      display: flex;
      align-items: flex-start;
      margin-top: 40rpx;
      .icon{
        width: 50rpx;
        height: 50rpx;
        margin-right: 40rpx;
      }
      .info-box{
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        min-height: 90rpx;
        flex: 1;
        .title{
          font-size: 32rpx;
        }
        .content{
          font-size: 24rpx;
          color: #3D3D3D;
        }
      }
      .time{
        font-size: 24rpx;
        color: #3D3D3D;
        margin-left: 40rpx;
        width: 180rpx;
        text-align: right;
      }
      &:last-of-type {
        padding-bottom: 40rpx;
      }
    }
  }
}
</style>

